import React from 'react'
import { Toast } from 'antd-mobile'
import { Search, NavBar, Gird, Button, Icon, Item, FlatList } from 'components'
import { post, msg } from '../../utils'
import './index.less'
import { isFunc } from 'muka'

export default class SearchView extends React.Component<any, any> {

    public state = {
        hots: [],
        hist: [],
        value: ''
    }

    public render(): JSX.Element {
        const { hots, hist, value } = this.state
        const header = (
            <div className="title flex_justify">
                <div className="flex">
                    <div className="flex_1">历史搜索</div>
                    <Icon type="delete" onClick={this.handleDeletHost} color="#999999" />
                </div>
            </div>
        )
        return (
            <div className="search">
                <NavBar
                    className="search_bar"
                    title={<Search onChange={this.handleChange} value={value} />}
                    right={<span className="search_bar_right" onClick={this.handleSearch}>搜索</span>}
                    fixed={true}
                />
                <Gird style={{ marginTop: 0, paddingBottom: '0.3rem' }}>
                    <div className="title flex_justify">
                        <div className="flex">
                            <div className="flex_1">热搜</div>
                        </div>
                    </div>
                    <div>
                        {
                            hots.map((item: any, index: number) => {
                                return (
                                    <Button className="btn" onClick={this.handleBtn.bind(this, item.name, item.id)} tick={false} type={item.is_hot_c ? 'error' : undefined} key={index}>{item.name}</Button>
                                )
                            })
                        }
                    </div>
                </Gird>
                <Gird style={{ height: hist.length ? 'auto' : '20rem' }}>
                    <FlatList
                        data={hist}
                        ListHeaderComponent={header}
                        EmptyShowHeader={false}
                        renderItem={(data: string, index: number) => {
                            return (
                                <Item className="search_list" title={data} key={index} onPress={this.handleMoveTo.bind(this, data)} />
                            )
                        }}
                        ListEmptyComponent={<img className="not_search" src={require('../../assets/not_search.png')} />}
                    />
                </Gird>
            </div >
        )
    }

    public componentDidMount() {
        this.getData()
        this.histData()
    }

    private handleBtn(value: string, id: number) {
        try {
            const { history } = this.props
            this.histData(value, () => {
                history.push(`/detail/category?name=${value}&id=${id}`)
            })
        } catch (e) {
            Toast.info('网络堵塞,请稍后重试', 1)
        }
    }

    private async getData() {
        try {
            const data = await post('searchapi/searchHot')
            this.setState({
                hots: data
            })
        } catch (e) {
            Toast.info('网络堵塞,请稍后重试', 1)
        }
    }

    private handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        this.setState({
            value: e.target.value
        })
    }

    private async histData(keyword?: string, callback?: () => void) {
        try {
            const data = await post('searchapi/keywordHistory', { keyword })
            this.setState({
                hist: data
            })
            if (isFunc(callback)) {
                callback()
            }
        } catch (e) {
            Toast.info('网络堵塞,请稍后重试', 1)
        }
    }

    private handleDeletHost = () => {
        msg('确定要删除历史搜索么？').then(() => {
            post('searchapi/keywordHistoryDel').then(() => {
                this.setState({
                    hist: []
                })
            })
        })
    }

    private handleSearch = () => {
        try {
            const { value, hots } = this.state
            const { history } = this.props
            if (!value) {
                const obj: any = hots[Math.round(Math.random() * (hots.length - 1))]
                history.push(`/detail/category?name=${obj.name}`)
            } else {
                this.histData(value, () => {
                    history.push(`/detail/category?name=${value}`)
                })
            }
        } catch (e) {
            Toast.info('网络堵塞,请稍后重试', 1)
        }
    }

    private handleMoveTo(data: any) {
        const { history } = this.props
        history.push(`/detail/category?name=${data}`)
    }
}